<?php

include "../inc/db_connect.php";
include "../inc/functions.php";
session_start();

// kontrola ci je prihlaseny user
if (empty($_SESSION['bmb_prihlas_id'])) {
    echo 1;
    exit;
}

// kontrola ci je prihlasenie neexpirovane
$sql = "SELECT * FROM prihlasenie WHERE id = '" . $_SESSION['bmb_prihlas_id'] . "'";
$result = MySQL_Query($sql);
$prihlasenie = MySQL_Fetch_Array($result);

if ($prihlasenie['datcas_do'] < date("Y-m-d H:i:s")) {
    echo 1;
    exit;
}

// udaje o prihlasenom userovi
$sql = "SELECT * FROM user WHERE id = '" . $prihlasenie['uid'] . "'";
$result = MySQL_Query($sql);
$user = MySQL_Fetch_Array($result);

// oddelenie pre ktore pocitame
$sql = "SELECT * FROM oddelenie WHERE id = '" . $_REQUEST['oddelenie'] . "'";
$result = MySQL_Query($sql);
$oddelenie = MySQL_Fetch_Array($result);

// zapis do logu
$myFile = '../logs/vypocet_nadcasov.txt'; // 
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, date("d/m/Y H:i:s") . ' - ');
fwrite($fh, $user['meno'] . ' ' . $user['priezvisko'] . ' (' . $user['mail'] . ') - ');
fwrite($fh, 'tyzden: ' . date('d/m/Y', $_REQUEST['date']) . ' - ');
fwrite($fh, $oddelenie['nazov']);
fwrite($fh, " - tyzdne: ");

// priprava pomocnej tabulky
$c_i = "CREATE TABLE IF NOT EXISTS `vystup` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `zam` int(11) NOT NULL,
  `date` varchar(16) COLLATE utf8_slovak_ci NOT NULL,
  `value` double NOT NULL,
  `full` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_slovak_ci AUTO_INCREMENT=1 ;";
$c_q = MySQL_Query($c_i);

// jej vycistenie ak existuje
$t_i = "TRUNCATE TABLE `vystup`";
$t_q = MySQL_Query($t_i);

$start = $zt = $kt = $_REQUEST['date'];

$zam_s = "SELECT * FROM z WHERE patri_k = '" . $_REQUEST['oddelenie'] . "'";
$zam_q = MySQL_Query($zam_s);
$zamestnanci = array();
while ($zam = MySQL_Fetch_Array($zam_q)) {
    $zamestnanci[] = $zam;
}

$debug_string = '';

while (date("n", $start) == date("n", $kt)) {
    fwrite($fh, date("d/m/Y", $zt) . ', ');
    $kt = $zt + (6 * 24 * 60 * 60);

    if ($kt > 1314489600) { //osetrenie ci je datum vacsi ako 28/8/2011, neviem uz preco som to sem daval ale asi to nejaky dovod malo
        $debug_string .= '<h3>'.date("d.m.Y", $zt).'-'.date("d.m.Y", $kt).'</h3>';
        foreach ($zamestnanci as $zam) {

            $prichod = explode('-', $zam['datum_prichodu']);
            $dPrichodu = date("U", mktime(0, 0, 0, $prichod[1], $prichod[2], $prichod[0]));
            if ($zam['datum_odchodu'] != '0000-00-00') {
                $odchod = explode('-', $zam['datum_odchodu']);
                $dOdchodu = date("U", mktime(0, 0, 0, $odchod[1], $odchod[2], $odchod[0]));
            } else {
                $dOdchodu = date("U", mktime(0, 0, 0, 12, 31, 2030)); // vymysleny datum ;-)
            }

            if (($dPrichodu <= $zt) && ($dOdchodu >= $kt)) {
                $hranica_od = $zt;
                $hranica_do = $kt;
                $malBytVpraci = 5;
            } else {
                if (($dPrichodu > $kt) || ($dOdchodu < $zt)) {
                    $malBytVpraci = 0;
                    $hranica_od = $kt;
                    $hranica_do = $zt;
                } else if (($dPrichodu > $zt) && ($dOdchodu < $kt)) {
                    $malBytVpraci = ($dOdchodu - $dPrichodu) / (24 * 60 * 60) + 1;
                    $malBytVpraci = $malBytVpraci - 2;
                    /*if ($zam['manager'] == 1) {
                        $malBytVpraci = $malBytVpraci - 2;
                    } else {
                        if ($malBytVpraci > 5)
                            $malBytVpraci = 5;
                    }*/
                    $hranica_od = $dPrichodu;
                    $hranica_do = $dOdchodu;
                } else if ($dPrichodu > $zt) {
                    $malBytVpraci = ($kt - $dPrichodu) / (24 * 60 * 60) + 1;
                    $malBytVpraci = $malBytVpraci - 2;
                    /*if ($zam['manager'] == 1) {
                        $malBytVpraci = $malBytVpraci - 2;
                    } else {
                        if ($malBytVpraci > 5)
                            $malBytVpraci = 5;
                    }*/
                    $hranica_od = $dPrichodu;
                    $hranica_do = $kt;
                } else if ($dOdchodu < $kt) {
                    $malBytVpraci = ($dOdchodu - $z) / (24 * 60 * 60) + 1;
                    $hranica_od = $zt;
                    $hranica_do = $dOdchodu;
                } else {
                    $malBytVpraci = 0;
                    $hranica_od = $kt;
                    $hranica_do = $zt;
                }
            }

            $sviatok_sql = "SELECT * FROM sviatok WHERE datum>='" . date("Y-m-d", $hranica_od) . "' AND datum<='" . date("Y-m-d", $hranica_do) . "'";
            $sviatok_result = mysql_query($sviatok_sql);
            $sviatok_pocet = mysql_num_rows($sviatok_result);
            $pocet_moznych_smien = $malBytVpraci;

            $sviatky = array();
            while ($sviatok = mysql_fetch_array($sviatok_result)) {
                $sviatky[] = $sviatok;
                $denVtyzdni = date('w', strtotime($sviatok['datum']));
                if ($denVtyzdni > 0 && $denVtyzdni < 6) {
                    $pocet_moznych_smien--;
                }
            }


            $d_s = "SELECT * FROM dochadzkazamfalk WHERE zid='" . $zam['id'] . "' AND date >= '" . $hranica_od . "' AND date <= '" . $hranica_do . "'";
            $d_q = MySQL_Query($d_s);
            $debug_string .= $zam['id'] . " - " . $zam['priezvisko'] . "    | datum prichodu: " . $zam['datum_prichodu'] . "   | datum odchodu: ".$zam['datum_odchodu']."   |   pocet moznych smien: " . $pocet_moznych_smien . "     |     ";
            $fond = $zam['fond'] * 60 * 60;
            $smena = $fond / 5;
            $nadcas = 0;
            $pocetSmien = $pocetPn = 0;
            while ($d = MySQL_Fetch_Array($d_q)) {

                if (($d['realOd'] != '') && ($d['realDo'] != '') && (($d['type'] == 'P') || ($d['type'] == 'SPL'))) {
                    $smenaVysledna = $smena + (0.5 * 3600);
                    $pocetSmien++;
                    $odrobene = zistiPocetSekund($d['realOd'], $d['realDo']);
                    $nadcasZaDen = $odrobene - $smenaVysledna;
                    if ($nadcasZaDen < 0) {
                        $n = $nadcasZaDen / 1800;
                        $n = (int) $n;
                        $n = $n / 2;
                        if (($nadcasZaDen % 1800) != 0) {
                            $n = $n - 0.5;
                        }
                        $nadcas += $n;
                    } elseif ($nadcasZaDen > 0) {
                        $n = $nadcasZaDen / 1800;
                        $n = (int) $n;
                        $n = $n / 2;
                        $nadcas += $n;
                    } else {
                        $nadcas += 0;
                    }
                } elseif (($d['type'] == 'D') || ($d['type'] == 'LV') || ($d['type'] == 'LD') || ($d['type'] == 'MD') || ($d['type'] == 'OT')) {
                    $pocetSmien++;
                } elseif ($d['type'] == 'PN') {
                    $pocetPn++;
                } elseif ($d['type'] == 'MOD') {
                    $mod_cez_sviatok = false;
                    $mod_cez_vikend = false;
                    if (date("w", $d['date']) == 6 || date("w", $d['date']) == 0)
                        $mod_cez_vikend = true;
                    else {
                        $sviatok_pocet = mysql_num_rows($sviatok_result);
                        foreach ($sviatky as $sviatok) {
                            if (date("Y-m-d", $d['date']) == $sviatok['datum']) {
                                $mod_cez_sviatok = true;
                            }
                        }
                    }
                    if ($mod_cez_sviatok || $mod_cez_vikend)
                        $nadcas += 4;
                    else
                        $pocetSmien++;
                }
            }

            if ($zam['manager'] == 1) {
                $pocet_na_ktory_kontrolujem = $pocet_moznych_smien;
            } else {
                $pocet_na_ktory_kontrolujem = $malBytVpraci;
            }

            if ($pocetPn >= $pocet_na_ktory_kontrolujem) {
                $pocetSmien = $pocet_na_ktory_kontrolujem;
            } else {
                if ($pocetSmien < $pocet_na_ktory_kontrolujem) {
                    if (($pocetSmien + $pocetPn) > $pocet_na_ktory_kontrolujem)
                        $pocetSmien = $pocet_na_ktory_kontrolujem;
                    else
                        $pocetSmien = $pocetSmien + $pocetPn;
                }
            }
            
            $chybajuciCas = (($pocet_na_ktory_kontrolujem - $pocetSmien) * $smena);
            $chybajuciCas = $chybajuciCas / 3600;
            $nadcas = $nadcas - $chybajuciCas;

            $debug_string .=  "pocet smien: " . $pocetSmien;
            $debug_string .=  "    | nadcas: " . $nadcas;
            $debug_string .=  "<br/>";
            
            $ul_i = "INSERT INTO vystup (id, zam, date, value, full, smeny, pn) VALUES (NULL, '" . $zam['id'] . "', '" . (date("d.m.Y", $zt).'-'.date("d.m.Y", $kt)) . "','" . $nadcas . "','" . ($malBytVpraci . "/" . $pocet_na_ktory_kontrolujem) . "','" . $pocetSmien . "', '".$pocetPn."')";
            $ul_q = MySQL_Query($ul_i);
            
            $s_s = "SELECT * FROM falknadcas WHERE zid = '" . $zam['id'] . "' AND date='" . $zt . "'";
            $s_q = MySQL_Query($s_s);
            $s = MySQL_Fetch_Array($s_q);
            if (isset($s['id'])) {
                $uloz_i = "UPDATE falknadcas SET kolko='" . $nadcas . "' WHERE zid='" . $zam['id'] . "' AND date='" . $zt . "'";
                $uloz_q = MySQL_Query($uloz_i);
            } else {
                $uloz_i = "INSERT INTO falknadcas (id, zid, date, mesiac, rok, kolko) VALUES (NULL, '" . $zam['id'] . "', '" . $zt . "','" . date("n", $_REQUEST['date']) . "','" . date("Y", $_REQUEST['date']) . "','" . $nadcas . "')";
                $uloz_q = MySQL_Query($uloz_i);
            }

            vypocitatNocne($zam['id'], $zt);
            vypocitatStravu($zam['id'], $zt);
            vypocitatSviatok($zam['id'], $zt);
            
        }
    }

    $zt = $zt - (7 * 24 * 60 * 60);
    $kt = $kt - (7 * 24 * 60 * 60);
    $debug_string .=  "<hr/>";
}
$debug_string .=  "<hr/>";
if ($_REQUEST['debug']=='1')
    echo $debug_string;
fwrite($fh, "\r\n");
fclose($fh);
echo 1;
?>
